<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

require_once 'db.php';

// 获取操作类型
$action = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? $_POST['action'] : '';
} else {
    $action = isset($_GET['action']) ? $_GET['action'] : '';
}

try {
    switch ($action) {
        // 获取团课详情
        case 'get_course_detail':
            $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
            if ($id <= 0) throw new Exception('参数错误');

            // 获取团课信息
            $sql = "SELECT c.*, cc.name as category_name, co.name as coach_name, co.avatar as coach_avatar 
                    FROM courses c
                    LEFT JOIN course_categories cc ON c.category_id = cc.id
                    LEFT JOIN coaches co ON c.coach_id = co.id
                    WHERE c.id = ? AND c.status = 1";
            
            $stmt = $conn->prepare($sql);
            if ($stmt === false) {
                throw new Exception('SQL预处理失败: ' . $conn->error);
            }

            if (!$stmt->bind_param("i", $id)) {
                throw new Exception('参数绑定失败: ' . $stmt->error);
            }

            if (!$stmt->execute()) {
                throw new Exception('查询执行失败: ' . $stmt->error);
            }

            $result = $stmt->get_result();
            
            if ($result->num_rows > 0) {
                $course = $result->fetch_assoc();
                echo json_encode([
                    'status' => 'success',
                    'course' => $course
                ]);
            } else {
                throw new Exception("课程不存在");
            }
            break;

        // 检查课程可预约状态
        case 'check_course_status':
            $course_id = isset($_GET['course_id']) ? intval($_GET['course_id']) : 0;
            $date = isset($_GET['date']) ? $_GET['date'] : '';
            
            if ($course_id <= 0 || !$date) throw new Exception('参数错误');

            // 检查课程状态
            $sql = "SELECT c.*, 
                    (SELECT COUNT(*) FROM bookings 
                     WHERE course_id = c.id 
                     AND booking_date = ? 
                     AND status != 3) as booked_count
                    FROM courses c 
                    WHERE c.id = ? AND c.status = 1";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("si", $date, $course_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows > 0) {
                $course = $result->fetch_assoc();
                $available = $course['booked_count'] < $course['capacity'];
                
                echo json_encode([
                    'status' => 'success',
                    'available' => $available,
                    'remaining' => $course['capacity'] - $course['booked_count']
                ]);
            } else {
                throw new Exception('课程不存在');
            }
            break;

        // 创建团课预约
        case 'create_booking':
            // 获取请求参数
            $user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
            $course_id = isset($_POST['course_id']) ? intval($_POST['course_id']) : 0;
            $booking_date = isset($_POST['booking_date']) ? $_POST['booking_date'] : '';
            $time_slot = isset($_POST['time_slot']) ? $_POST['time_slot'] : '';

            // 参数验证
            if (!$user_id || !$course_id || !$booking_date || !$time_slot) {
                throw new Exception('参数错误');
            }

            // 获取课程信息
            $course_sql = "SELECT c.*, 
                           (SELECT COUNT(*) FROM bookings 
                            WHERE course_id = c.id 
                            AND booking_date = ? 
                            AND status != 3) as current_booked
                           FROM courses c 
                           WHERE c.id = ? AND c.status = 1";
            $course_stmt = $conn->prepare($course_sql);
            $course_stmt->bind_param("si", $booking_date, $course_id);
            $course_stmt->execute();
            $course_result = $course_stmt->get_result();
            
            if ($course_result->num_rows == 0) {
                throw new Exception('课程不存在');
            }
            
            $course = $course_result->fetch_assoc();
            
            // 检查课程容量
            if ($course['current_booked'] >= $course['capacity']) {
                throw new Exception('该课程已约满');
            }

            // 检查是否重复预约
            $check_sql = "SELECT id FROM bookings 
                          WHERE user_id = ? 
                          AND course_id = ? 
                          AND booking_date = ? 
                          AND status != 3";
            $check_stmt = $conn->prepare($check_sql);
            $check_stmt->bind_param("iis", $user_id, $course_id, $booking_date);
            $check_stmt->execute();
            if ($check_stmt->get_result()->num_rows > 0) {
                throw new Exception('您已预约过该课程');
            }

            // 开始事务
            $conn->begin_transaction();

            try {
                // 创建预约记录
                $sql = "INSERT INTO bookings (user_id, course_id, type, booking_date, 
                        time_slot, status, price, created_at) 
                        VALUES (?, ?, 2, ?, ?, 0, ?, NOW())";
                $stmt = $conn->prepare($sql);
                if ($stmt === false) {
                    throw new Exception('SQL预处理失败: ' . $conn->error);
                }
                $stmt->bind_param("iissd", $user_id, $course_id, $booking_date, 
                                 $time_slot, $course['price']);
                if (!$stmt->execute()) {
                    throw new Exception('预约创建失败: ' . $stmt->error);
                }
                // 更新课程已预约人数
                $update_sql = "UPDATE courses SET booked_count = booked_count + 1 
                              WHERE id = ?";
                $update_stmt = $conn->prepare($update_sql);
                $update_stmt->bind_param("i", $course_id);
                
                if (!$update_stmt->execute()) {
                    throw new Exception('更新课程预约人数失败: ' . $update_stmt->error);
                }
                // 提交事务
                $conn->commit();
                
                echo json_encode([
                    'status' => 'success',
                    'message' => '预约成功'
                ]);
            } catch (Exception $e) {
                $conn->rollback();
                throw $e;
            }
            break;

        default:
            throw new Exception('未知的操作类型');
    }

} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
} finally {
    if (isset($stmt) && $stmt !== false) $stmt->close();
    if (isset($course_stmt) && $course_stmt !== false) $course_stmt->close();
    if (isset($check_stmt) && $check_stmt !== false) $check_stmt->close();
    if (isset($conn)) $conn->close();
}
?> 